package com.zdsoft.site.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zdsoft.site.dao.UserDao;
import com.zdsoft.site.service.UserService;

@Service
public class UserServiceImpl implements UserService,UserDetailsService {
	@Autowired
	private UserDao userDao;
	@Override
	@Transactional
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//1.搜索数据库以匹配用户登录名.
		//2.构造Security专用的User
		com.zdsoft.site.domain.User u=userDao.findByCode(username);
		UserDetails user=new User(u.getUsername(), u.getPassword(),true,true,true,true,getAuthorities(1));
		return user;
	}
	/**
	 * 获得访问角色权限
     * @param access 
     */  
    public Collection<GrantedAuthority> getAuthorities(Integer access) {  
        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);  
        //所有的用户默认拥有ROLE_USER权限 
        authList.add(new SimpleGrantedAuthority("ROLE_USER"));  
        // 如果参数access为1.则拥有ROLE_ADMIN权限  
        if (access.compareTo(1) == 0) {  
            authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));  
        }  
        return authList;  
    }  
}
